import 'dart:io';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:share_fit/app/helper/ext/tr_ext.dart';
import 'package:share_fit/app/tools/color_const.dart';
import 'package:share_fit/app/ute/model/device_info.dart';
import 'package:share_fit/app/ute/uteped_device.dart';
import 'package:share_fit/generated/locales.g.dart';
import 'package:sprintf/sprintf.dart';

import 'device_logic.dart';

class DevicePage extends StatelessWidget {
  /// 设备页面
  DevicePage({super.key});

  final logic = Get.put(DeviceLogic());
  final state = Get
      .find<DeviceLogic>()
      .state;

  @override
  Widget build(BuildContext context) {
    return Obx(() =>
    state.hasConnectedDevice.value
        ? _deviceView(context)
        : _emptyDeviceView(context));
  }

  Widget _emptyDeviceView(BuildContext context) {
    /// 没有设备连接的时候显示添加设备
    return Scaffold(
      appBar: AppBar(
          backgroundColor: Colors.transparent,
      ),
      body: Padding(
        padding: EdgeInsets.only(left: 43.w, right: 42.w),
        child: Container(
          constraints: BoxConstraints(minHeight: 588.h, maxHeight: 688.h),
          decoration: BoxDecoration(
            color: Colors.white,
            borderRadius: BorderRadius.circular(15),
          ),
          child: Stack(
            children: [
              Container(
                alignment: Alignment.topCenter,
                child: InkWell(
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.center,
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      Image.asset(
                        'assets/images/device/device_add.png',
                        height: 218.h,
                        fit: BoxFit.cover,
                      ),
                      SizedBox(height: 40.h),
                      Text(
                        LocaleKeys.device_add.ts,
                        style: TextStyle(
                          fontSize: 54.sp,
                          color: Colors.grey,
                        ),
                      ),
                      SizedBox(height: 57.h),
                      Text(
                        LocaleKeys.device_bind.ts,
                        style: TextStyle(
                          fontSize: 42.sp,
                          color: Colors.black,
                        ),
                      ),
                    ],
                  ),
                  onTap: () async {
                    await logic.onItemTaped('/device/search');
                  },
                ),
              ),
              Positioned(
                top: 0,
                right: 0,
                child: InkWell(
                  child: Container(
                    alignment: Alignment.topRight,
                    height: 240.h,
                    width: 240.w,
                    child: Padding(
                      padding: EdgeInsets.only(top: 38.h, right: 38.w),
                      child: Row(
                        crossAxisAlignment: CrossAxisAlignment.end,
                        mainAxisAlignment: MainAxisAlignment.end,
                        children: [
                          Image.asset(
                            'assets/images/device/device_qrcode.png',
                            width: 68.w,
                            height: 68.h,
                          )
                        ],
                      ),
                    ),
                  ),
                  onTap: () {
                    logic.onItemTaped('/device/scan');
                  },
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }

  // 部分功能按产品要求屏蔽掉
  Widget _deviceView(BuildContext context) {
    List uiListData1 = [
      {
        "name": LocaleKeys.settings_dial.ts,
        "icon": "assets/images/device/ic_device_dail.png",
        "route": "/device/settings/dial"
      },
      {
        "name": LocaleKeys.settings_hr.ts,
        "icon": "assets/images/device/ic_device_hr.png",
        "route": "/device/settings/hr"
      },
      // {
      //   "name": LocaleKeys.settings_sleep.ts,
      //   "icon": "assets/images/device/ic_device_sleep.png",
      //   "route": "/device/settings/sleep"
      // },
      {
        "name": LocaleKeys.settings_spo2.ts,
        "icon": "assets/images/device/ic_device_spo2.png",
        "route": "/device/settings/spo2"
      },
      {
        "name": LocaleKeys.settings_pressure.ts,
        "icon": "assets/images/device/ic_pressure.png",
        "route": "/device/settings/pressure"
      },
      // {"name": LocaleKeys.settings_weight.ts, "icon": "assets/images/device/ic_device_weight.png", "route": "/device/settings/weight"},
      // {"name": LocaleKeys.settings_weather.ts, "icon": "assets/images/device/ic_device_weather.png", "route": "/device/settings/weather"},
      // {"name": LocaleKeys.settings_time.ts, "icon": "assets/images/device/ic_device_time.png", "route": "/device/settings/time"},

    ];

    if (Platform.isAndroid) {
      uiListData1.add({
        "name": LocaleKeys.settings_permission.ts,
        "icon": "assets/images/device/ic_device_permission.png",
        "route": "/device/settings/permission"
      });
    }

    List uiListData2 = [
      {
        "name": LocaleKeys.settings_contacts.ts,
        "icon": "assets/images/device/ic_device_contacts.png",
        "route": "/device/settings/contacts"
      },
      // {
      //   "name": LocaleKeys.settings_menstrual.ts,
      //   "icon": "assets/images/device/ic_device_menstrual.png",
      //   "route": "/device/settings/menstrual"
      // },
      {
        "name": LocaleKeys.settings_call_remind.ts,
        "icon": "assets/images/device/ic_call_remind.png",
        "route": "/device/settings/call_remind"
      },
      {
        "name": LocaleKeys.settings_sms_remind.ts,
        "icon": "assets/images/device/ic_sms_remind.png",
        "route": "/device/settings/sms_remind"
      },
      {
        "name": LocaleKeys.settings_app_remind.ts,
        "icon": "assets/images/device/ic_app_remind.png",
        "route": "/device/settings/app_remind"
      },
      {
        "name": LocaleKeys.settings_sedentary_remind.ts,
        "icon": "assets/images/device/ic_sedentary_remind.png",
        "route": "/device/settings/sedentary_remind"
      },
      // {"name": LocaleKeys.settings_drink_remind.ts, "icon": "assets/images/device/ic_drink_remind.png", "route": "/device/settings/drink_remind"},
    ];

    List uiListData3 = [
      // {"name": LocaleKeys.remind.ts, "icon": "assets/images/device/ic_device_remind.png", "route": "/device/settings/remind"},
      // {"name": LocaleKeys.measure.ts, "icon": "assets/images/device/ic_device_measure.png", "route": "/device/settings/measure"},
      {
        "name": LocaleKeys.settings_sos.ts,
        "icon": "assets/images/device/ic_sos.png",
        "route": "/device/settings/sos"
      },
    ];

    // iOS不支持短信快捷回复
    if (Platform.isAndroid) {
      uiListData3.insert(0, {
        "name": LocaleKeys.settings_quick_reply.ts,
        "icon": "assets/images/device/ic_quick_reply.png",
        "route": "/device/settings/quick_reply"
      });
    }

    List uiListData4 = [
      {
        "name": LocaleKeys.ai_alarm.ts,
        "icon": "assets/images/device/icon_device_alarm.png",
        "route": "/device/alarm"
      },
      // {"name": LocaleKeys.light_lift.ts, "icon": "assets/images/device/icon_light.png", "route": "/device/light"},
      // {"name": LocaleKeys.settings_dnd_mode.ts, "icon": "assets/images/device/ic_dnd_mode.png", "route": "/device/settings/dnd"},
      {
        "name": LocaleKeys.settings_more.ts,
        "icon": "assets/images/device/ic_device_settings_more.png",
        "route": "/device/settings/more"
      },
      {
        "name": LocaleKeys.firmware_upgrade.ts,
        "icon": "assets/images/device/ic_firmware_upgrade.png",
        "route": "/device/settings/upgrade"
      },
      {
        "name": LocaleKeys.restoration_device_setting.ts,
        "icon": "assets/images/device/ic_device_reset.png",
        "route": "/device/settings/reset"
      },
    ];

    /// 设备连接情况下显示手表信息及功能列表
    final theme = Theme.of(context);
    return Scaffold(
      appBar: AppBar(
        title: Text(LocaleKeys.device.ts, style: theme.textTheme.titleLarge),
          actions: [
            Obx(() {
              return Offstage(
                offstage: !state.isConnected.value,
                child: Container(
                  padding: EdgeInsets.only(top: 20.h, right: 83.w),
                  child: Image.asset(
                      "assets/images/device/ic_device_connected.png",
                    width: 66.w,
                    height: 66.w
                  ),
                ),
              );
            })
          ]
      ),
      body: SafeArea(
          child: SingleChildScrollView(
              child: Padding(
                padding: EdgeInsets.all(42.w),
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        _buildDeviceInfo(context),
                        SizedBox(height: 40.h),
                        Column(
                          children: uiListData1
                              .asMap()
                              .map((index, item) =>
                              MapEntry(
                                  index,
                                  _buildListTile(item, index == 0,
                                      index == uiListData1.length - 1)))
                              .values
                              .toList(),
                        ),
                        SizedBox(height: 40.h),
                        Column(
                          children: uiListData2
                              .asMap()
                              .map((index, item) =>
                              MapEntry(
                                  index,
                                  _buildListTile(item, index == 0,
                                      index == uiListData2.length - 1)))
                              .values
                              .toList(),
                        ),
                        SizedBox(height: 40.h),
                        Column(
                          children: uiListData3
                              .asMap()
                              .map((index, item) =>
                              MapEntry(
                                  index,
                                  _buildListTile(item, index == 0,
                                      index == uiListData3.length - 1)))
                              .values
                              .toList(),
                        ),
                        SizedBox(height: 40.h),
                        Column(
                          children: uiListData4
                              .asMap()
                              .map((index, item) =>
                              MapEntry(
                                  index,
                                  _buildListTile(item, index == 0,
                                      index == uiListData4.length - 1)))
                              .values
                              .toList(),
                        ),

                        SizedBox(height: 80.h),
                        SizedBox(
                          width: double.infinity,
                          child: SizedBox(
                            child: CupertinoButton(
                              borderRadius: BorderRadius.circular(40.w),
                              color: ColorConst.accentColor,
                              onPressed: () {
                                showDialog(
                                    context: Get.overlayContext!,
                                    barrierDismissible: false,
                                    builder: (BuildContext context) {
                                      return _buildUnbindDialog(context,
                                          UTEPedDevice.instance.deviceInfo);
                                    });
                              },
                              child: Text(LocaleKeys.device_unbind.ts,
                                style: const TextStyle(
                                    color: Colors.white, fontSize: 17),
                              ),
                            ),
                          ),
                        ),
                        SizedBox(height: 40.h),
                      ],
                    ),
                  ],
                ),
              ))),
    );
  }

  Widget _buildDeviceInfo(BuildContext context) {
    return Ink(
        decoration: BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.circular(20),
        ),
        child: InkResponse(
          splashColor: Colors.white,
          borderRadius: BorderRadius.circular(20),
          highlightShape: BoxShape.rectangle,
          highlightColor: Colors.white,
          containedInkWell: true,
          child: Container(
            height: 450.h,
            padding: EdgeInsets.only(
                left: 34.w, top: 34.h, bottom: 34.h),
            decoration: BoxDecoration(
                borderRadius: BorderRadius.circular(8)),
            child: Stack(
              children: [
                Row(
                  children: [
                    SizedBox(
                      width: 298.w,
                      height: 298.w,
                      child: GetBuilder<DeviceLogic>(
                        id: "deviceIcon",
                          builder: (logic) {
                        return Center(
                          child: Image.asset(state.deviceIcon),
                        );
                      }),
                    ),
                    SizedBox(width: 43.w),
                    Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      mainAxisAlignment: MainAxisAlignment.start,
                      children: [
                        SizedBox(height: 124.h),
                        Obx(() =>
                            Text(state.name.value,
                                maxLines: 2,
                                style: TextStyle(
                                    fontSize: 60.sp,
                                    color: const Color(0xFF000013)))),
                        Obx(() =>
                            Text(
                                sprintf(
                                    LocaleKeys.device_mac_address.ts,
                                    [state.address]),
                                style: TextStyle(
                                    fontSize: 48.sp,
                                    color: const Color(0xFF707083)))),
                      ],
                    ),
                  ],
                ),
                Positioned(
                  right: 30.w,
                  child: Obx(() =>
                      Text(
                        state.battery.value.isNotEmpty ? sprintf(
                            LocaleKeys.device_battery_level.ts,
                            [state.battery.value]) : "",
                        style: TextStyle(
                            fontSize: 50.sp,
                            color: const Color(0xFF707083)),
                      )),
                ),
              ],
            ),
          ),
          onTap: () {
            // logic.onDeviceInfoTap();
          },
          onDoubleTap: () {
            logic.onDeviceInfoDoubleTap();
          },
        ));
  }

  Widget _buildListTile(item, isFirst, isLast) {
    var borderRadius = BorderRadius.circular(0);
    if (isFirst) {
      borderRadius = const BorderRadius.vertical(top: Radius.circular(8));
    }
    else if (isLast) {
      borderRadius = const BorderRadius.vertical(bottom: Radius.circular(8));
    }

    return Ink(
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: borderRadius,
      ),
      child: InkResponse(
        splashColor: ColorConst.activeColor,
        borderRadius: borderRadius,
        highlightShape: BoxShape.rectangle,
        highlightColor: ColorConst.activeColor,
        containedInkWell: true,
        child: ListTile(
          contentPadding: EdgeInsets.only(left: 29.w),
          leading: SizedBox(
            width: 100.w,
            height: 100.h,
            child: Center(
              child: Image.asset(item['icon']),
            ),
          ),
          title: Text(item['name'], style: TextStyle(fontSize: 48.sp)),
          trailing: Container(
            padding: EdgeInsets.only(right: 32.w),
            width: 70,
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                GetBuilder<DeviceLogic>(
                    id: "upgradeItem",
                    builder: (logic) {
                      return state.isUpgradable &&
                          item["route"].contains("upgrade") ? Container(
                        padding: EdgeInsets.symmetric(
                            vertical: 4.h, horizontal: 10.w),
                        decoration: BoxDecoration(
                          color: Colors.red,
                          borderRadius: BorderRadius.all(Radius.circular(40.r)),
                        ),
                        child: Text("NEW", style: TextStyle(color: Colors.white,
                            fontSize: 33.sp),),
                      ) : const Text("");
                    }),
                const Icon(
                  Icons.arrow_forward_ios,
                  size: 16,
                ),
              ],
            ),
          ),
        ),
        onTap: () => logic.onItemTaped(item['route']),
      ),
    );
  }

  Widget _buildUnbindDialog(BuildContext context, DeviceInfo item) {
    return Material(
      type: MaterialType.transparency,
      child: Center(
        child: SizedBox(
          width: 916.w,
          height: Platform.isIOS ? 886.h : 736.w,
          child: Container(
            decoration: const ShapeDecoration(
              color: Color(0xffffffff),
              shape: RoundedRectangleBorder(
                borderRadius: BorderRadius.all(
                  Radius.circular(20.0),
                ),
              ),
            ),
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              crossAxisAlignment: CrossAxisAlignment.center,
              children: <Widget>[
                Text(LocaleKeys.device_unbind_title.ts,
                    style: TextStyle(fontSize: 54.sp)),
                SizedBox(height: 97.w),
                _buildUnbindDialogContent(context),
                SizedBox(height: 126.w),
                Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  crossAxisAlignment: CrossAxisAlignment.center,
                  children: [
                    ElevatedButton(
                      style: ButtonStyle(
                        minimumSize:
                        MaterialStateProperty.all(Size(383.w, 136.w)),
                        backgroundColor:
                        MaterialStateProperty.all(ColorConst.dialogBtnBg),
                        foregroundColor:
                        MaterialStateProperty.resolveWith<Color>(
                              (Set<MaterialState> states) {
                            if (states.contains(MaterialState.pressed)) {
                              return ColorConst.btnFontColorPressed;
                            }
                            return ColorConst.btnFontColor;
                          },
                        ),
                        overlayColor:
                        MaterialStateProperty.all(ColorConst.accentColor),
                        shape: MaterialStateProperty.all(
                            const RoundedRectangleBorder(
                              borderRadius: BorderRadius.all(
                                Radius.circular(10.0),
                              ),
                            )),
                      ),
                      child: Text(
                        LocaleKeys.device_unbind.ts,
                        style: TextStyle(fontSize: 42.sp),
                      ),
                      onPressed: () {
                        Navigator.pop(context);
                        logic.unbindDevice(item.address);
                      },
                    ),
                    SizedBox(width: 39.w),
                    ElevatedButton(
                      style: ButtonStyle(
                        minimumSize:
                        MaterialStateProperty.all(Size(383.w, 136.w)),
                        backgroundColor:
                        MaterialStateProperty.all(ColorConst.dialogBtnBg),
                        foregroundColor:
                        MaterialStateProperty.resolveWith<Color>(
                              (Set<MaterialState> states) {
                            if (states.contains(MaterialState.pressed)) {
                              return ColorConst.btnFontColorPressed;
                            }
                            return ColorConst.btnFontColor;
                          },
                        ),
                        overlayColor:
                        MaterialStateProperty.all(ColorConst.accentColor),
                        shape: MaterialStateProperty.all(
                            const RoundedRectangleBorder(
                              borderRadius: BorderRadius.all(
                                Radius.circular(10.0),
                              ),
                            )),
                      ),
                      child: Text(
                        LocaleKeys.cancel.ts,
                        style: TextStyle(
                            color: ColorConst.btnFontColor, fontSize: 42.sp),
                      ),
                      onPressed: () {
                        Navigator.pop(context);
                      },
                    ),
                  ],
                )
              ],
            ),
          ),
        ),
      ),
    );
  }

  _buildUnbindDialogContent(BuildContext context) {
    if (Platform.isIOS) {
      return Container(
        padding: EdgeInsets.symmetric(vertical: 0.0, horizontal: 42.w),
        child: Text(LocaleKeys.unbind_warning_note.ts,
            style: TextStyle(fontSize: 42.sp)),
      );
    }
    else {
      return Image.asset('assets/images/device/device_unbind_icon.png',
          width: 184.w, height: 204.h);
    }
  }
}
